package com.zlt.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CORSFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String method = request.getMethod();
        //设置响应头
        //设置哪些地方的请求可以跨域 * 表示任意请求  多个值可以用,隔开
        //"http://localhost:9999,http://localhost:8888"

        response.setHeader("Access-Control-Allow-Origin","*");
        System.out.println("来自于哪里的请求====:"+request.getHeader("Origin"));
        //是否允许携带cookie
        response.setHeader("Access-Control-Allow-Credentials","true");
        // 允许的请求方式
        response.setHeader("Access-Control-Allow-Methods","GET,POST,HEAD,OPTIONS");
        //允许的请求头
        response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type,token,Accept, Connection, User-Agent, Cookie");
        //允许浏览器获取的响应头
        response.setHeader("Access-Control-Expose-Headers","token");
        // 超时时间
        response.setHeader("Access-Control-Max-Age","362880");
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return;
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("CORS filter init");
    }

}